/**
 * Created by Administrator on 2017/9/21.
 */
$(function() {

    var winnerId='' ;

    /*奖品列表*/
    var lotteryTpl = $('#lottery-template').html();
    var lotteryCmp = Handlebars.compile(lotteryTpl);
    /*中奖名单*/
    var personTpl = $('#scrollPrensent').html();
    var personCmp = Handlebars.compile(personTpl);

    /*中奖内容*/
    var lotteryAlertTpl = $('#tur-alert-box').html();
    var lotteryAlertCmp = Handlebars.compile(lotteryAlertTpl);

    var loading = dialog.loading();
    $.ajax({
        url:C.interface.giftLists,
        type: 'post',
        dataType: 'json',
        data: {
            token: C.token
        },
        complete:function () {
            loading.close();
        },
        success: function (response) {
            if (response.errorCode == '200'){
                var data = response.data;
                console.log(data);
                //奖品列表
                var lotteryList = data.info;
                //中奖人员名单
                var lotteryPerson = data.winners;

                $('#lottery').html(lotteryCmp(lotteryList));
                $('#scroll-list-ul').html(personCmp(lotteryPerson));
                //无缝滚动
                $('.scroll-list li:even').addClass('lieven');
                $(function(){
                    $(".scroll-list").myScroll({
                        speed:40, //数值越大，速度越慢
                        rowHeight:30 //li的高度
                    });
                });

                var clickBtn = "<li class='lottery-unit lottery-unit gift5'>\
                <div class='tur-zhuan'>赚</div>\
                    <div>中奖率100%</div>\
                    </li>";
                $('.lottery-unit').eq(3).after(clickBtn);
                $('.lottery-unit').eq(0).addClass('lottery-unit-0').addClass('gift1').find('img').addClass('gift1');
                $('.lottery-unit').eq(1).addClass('lottery-unit-1');
                $('.lottery-unit').eq(2).addClass('lottery-unit-2').addClass('gift3').find('img').addClass('gift3');
                $('.lottery-unit').eq(3).addClass('lottery-unit-7');
                $('.lottery-unit').eq(5).addClass('lottery-unit-3');
                $('.lottery-unit').eq(6).addClass('lottery-unit-6').addClass('gift7');
                $('.lottery-unit').eq(7).addClass('lottery-unit-5');
                $('.lottery-unit').eq(8).addClass('lottery-unit-4').addClass('gift9');

                $(".gift5").bind('click',function (event) {
                    event.preventDefault();
                    $('.pay-mask').show(200);
                    $('#pay-box').show(200);
                });

                $('.close-img>img').click(function () {
                    $('.pay-mask').hide(200);
                    $('#pay-box').hide(200);
                });

                $('#submit-pay').click(function () {
                    var payType = $('input[name=radio1]:checked').val();
                    console.log(payType);
                    $('.pay-mask').hide();
                    $('#pay-box').hide();
                    //开始抽奖
                    goLottery();

                    //拉起支付
                    //goPay(10,0,payType,'goLottery','0','赚一下');
                });



            }
        }
    });


    /**
     * 这里调用抽奖的方法
     * */
    function goLottery() {
        lottery.init('lottery');
        if (lottery.click) { //click控制一次抽奖过程中不能重复点击抽奖按钮，后面的点击不响应
            return false;
        } else {
            lottery.getLottery();
            return false;
        }
    }

    var lottery = {
        place: 0, //请求后指定停留在某个位置
        click: false, //默认值为false可抽奖，防止重复点击
        index: -1, //当前转动到哪个位置，起点位置
        count: 0, //总共有多少个位置
        timer: 0, //setTimeout的ID，用clearTimeout清除
        speed: 20, //初始转动速度
        times: 0, //转动次数
        cycle: 50, //转动基本次数：即至少需要转动多少次再进入抽奖环节
        prize: -1, //中奖位置
        init: function(id) {
            if ($("#" + id).find(".lottery-unit").length > 0) {
                $lottery = $("#" + id);
                $units = $lottery.find(".lottery-unit");
                this.obj = $lottery;
                this.count = $units.length;
                $lottery.find(".lottery-unit-" + this.index).addClass("active");
            };
        },
        roll: function() {
            var index = this.index,
                count = this.count,
                lottery = this.obj;
            $(lottery).find(".lottery-unit-" + index).removeClass("active");
            index += 1;
            if (index > count - 1) {
                index = 0;
            };
            $(lottery).find(".lottery-unit-" + index).addClass("active");
            this.index = index;
            return false;
        },
        stop: function() {
            lottery.times += 1;
            lottery.roll(); //转动过程调用的是lottery的roll方法，这里是第一次调用初始化
            if (lottery.times > lottery.cycle + 10 && lottery.prize == lottery.index) {
                clearTimeout(lottery.timer);
                lottery.prize = -1;
                lottery.times = 0;
                lottery.click = false;
                //可以在这个位置写上中奖弹框，这个是转盘停止时触发事件
                //console.log('您抽中了第' + lottery.place + '个奖品');
                giftShow();
                //关闭中奖弹框
                $('.tur-close-alert').click(giftClose);
                $('.gift-pull').click(function () {
                    window.location.href = 'turnplate_info.html?winnerId='+winnerId
                });
            } else {
                if (lottery.times < lottery.cycle) {
                    lottery.speed -= 10;
                } else if (lottery.times == lottery.cycle) {
                    //lottery.place = Math.random() * (lottery.count) | 0; //案例中奖物品通过一个随机数生成
                    lottery.prize = lottery.place;  //这个可以通过ajax请求回来的数据赋值给lottery.place
                } else {
                    if (lottery.times > lottery.cycle + 10 && ((lottery.prize == 0 && lottery.index == 7) || lottery.prize == lottery.index + 1)) {
                        lottery.speed += 110;
                    } else {
                        lottery.speed += 20;
                    }
                }
                if (lottery.speed < 40) {
                    lottery.speed = 40;
                };
                lottery.timer = setTimeout(lottery.stop, lottery.speed); //循环调用
            }
            return false;
        },
        getLottery: function() {//ajax请求中奖接口，本案例注释便于案例正常展示效果，实际中可参考注释的代码

            $.ajax({
                url: C.interface.choujiang,
                type: 'post',
                dataType: 'json',
                data: {
                    phone: C.phone,
                    pwd: C.pwd,
                    token: C.token
                },
                success:function (response) {
                    if (response.errorCode == '200'){
                        var data = response.data;
                        /**
                         * value中奖奖品Id
                         * winnerId 中奖人Id
                         * */
                        var value = parseInt(data.gift.activity_id);
                        winnerId = data.winnerId;
                        console.log(value);
                        switch (value){
                            case 1 :
                                lottery.place = 0;
                                break;
                            case 2 :
                                lottery.place = 1;
                                break;
                            case 3 :
                                lottery.place = 2;
                                break;
                            case 4 :
                                lottery.place = 7;
                                break;
                            case 5 :
                                lottery.place = 3;
                                break;
                            case 6 :
                                lottery.place = 6;
                                break;
                            case 7 :
                                lottery.place = 5;
                                break;
                            case 8 :
                                lottery.place = 4;
                                break;
                        }

                        /*中奖弹框内容填充*/
                        $('.tur-alert-box').html(lotteryAlertCmp(data.gift));
                    }
                }
            });
            lottery.speed = 100;
            lottery.stop(); //转圈过程不响应click事件，会将click置为false
            lottery.click = true; //一次抽奖完成后，设置click为true，可继续抽奖
        }
    };

    function giftShow() {
        $('.tur-mask').show();
        $('.tur-alert-box').show();
    }
    function giftClose() {
        $('.tur-mask').hide();
        $('.tur-alert-box').hide();
    }


});






//登录ajax
/*$.ajax({
    url: C.interface.loginIn,
    type: 'post',
    dataType: 'json',
    data: {
        phone: C.phone,
        pwd: C.pwd,
        token: C.token,
    },
    success: function (response) {
        if (response.errorCode == '200') {

        } else if (response.errorCode == '0') {

        } else {
            alert(response.errorMsg);
        }
    }
});*/

//抽奖商品渲染
/*var lotteryTpl = $('#cj1').html();
var lotteryCmp = Handlebars.compile(lotteryTpl);
//滚动商品渲染
var lotteryScroll = $('#scrollPrensent').html();
var lotteryScrollCmp = Handlebars.compile(lotteryScroll);


//中奖渲染
var choujiangTpl = $('#tur-alert-box').html();
var choujiangCmp = Handlebars.compile(choujiangTpl);


//关闭中奖弹框
$('.tur-close-alert').click(giftClose);

//中奖弹框显示
function giftShow() {
    $('.tur-mask').show();
    $('.tur-alert-box').show();
}
//关闭中奖弹框
function giftClose() {
    $('.tur-mask').hide();
    $('.tur-alert-box').hide();
    location = location
}

//点击立即领取
$('.gift-pull').click(function () {
    window.location.href = 'turnplate_info.html'
});

var loading = dialog.loading();
//转一下列表
$.ajax({
    url: C.interface.giftLists,
    type: 'post',
    dataType: 'json',
    data: {
        token: C.token,
    },
    complete:function () {
        loading.close();
    },
    success: function (response) {
        if (response.errorCode == '200') {
            var data = response.data;
            //抽奖商品渲染
            $('.cj1').html(lotteryCmp(data.info));
            // 滚动效果渲染
            $('#scroll-list-ul').html(lotteryScrollCmp(data.winners));
            setTimeout(() => {
                $('.cj1').show(200);
            }, 500);

            // 抽奖js
            (function ($, window, document, undefined) {
                    var LuckDraw = function (ele, opt) {
                        this.$element = ele,
                            this.defaults = {
                                row: 3, //行
                                column: 3, //列
                                spacing: 0,
                                click: null,
                                time: 3,
                                end: function (e) { }
                            },
                            this.target,
                            this.options = $.extend({}, this.defaults, opt);
                    }
                    LuckDraw.prototype = {
                        init: function () {
                            var $this = this.$element;
                            var row = this.options.row;
                            var col = this.options.column;
                            var spacing = this.options.spacing;
                            var click = this.options.click;
                            var allNumber = 2 * (row + col) - 4;
                            var line = row - 2;//除去上下de行数
                            var length = $this.children('li').length;
                            var options = this.options;

                            // if(length < allNumber){
                            // 	for(var i=length;i<=(allNumber-length);i++){
                            // 		$this.append("<li>"+(i+1)+"</li>");
                            // 	}
                            // }
                            var children = $this.children('li');
                            var width = children.eq(0).width() || 0;
                            var height = children.eq(0).height() || 0;

                            //元素初始化
                            $this.css({
                                position: 'relative',
                                width: col * width + (col - 1) * spacing,
                                height: row * height + (row - 1) * spacing
                            });
                            children.css({
                                position: 'absolute'
                            });


                            if (line == 0) {
                                initOne();
                            } else {
                                initTwo();
                            }

                            //初始化函数
                            //此时分成4个部分，上、右、下、左
                            //上： 0  ~  col-1
                            //右： col ~ col+line
                            //下： col+line+1 ~ 2*col+line-1
                            //左： else
                            //如果只有两行
                            //此时分成4个部分，上、右、下、左

                            function initOne() {
                                children.each(function (index) {
                                    if (index >= 0 && index <= (col - 1)) {
                                        $(this).css({
                                            top: 0,
                                            left: index * width + index * spacing
                                        });
                                    } else {
                                        $(this).css({
                                            bottom: 0,
                                            right: index % col * width
                                        });
                                    }
                                });
                            }
                            //如果大于两行
                            function initTwo() {
                                children.each(function (index) {
                                    if (index >= 0 && index <= (col - 1)) {
                                        $(this).css({
                                            top: 0,
                                            left: index * width + index * spacing
                                        });
                                    } else if (index >= col && index <= (col + line - 1)) {
                                        $(this).css({
                                            top: ((index + 1 - col)) * (height + spacing),
                                            right: 0
                                        });
                                    } else if (index >= (col + line) && index <= (2 * col + line - 1)) {
                                        $(this).css({
                                            bottom: 0,
                                            right: (index - ((col + line))) * (width + spacing)
                                        });
                                    } else {
                                        $(this).css({
                                            left: 0,
                                            bottom: (index - (2 * col + line - 1)) * (height + spacing)
                                        });
                                    }
                                });
                            }


                            var target = $this.target || Math.floor(Math.random() * allNumber + 1); //目标，指定或随机
                            var ix = 0; //位置
                            var stop;
                            var flg = false; //抽奖是否正在运行
                            /!*
                                加速度公式
                                v1 = v0 + a*t;注意加速度的v代表时间
                                此时的t可以我们自己定义，所以是常量，所以只需要求a的值
                            *!/
                            var a = -25.0;
                            var v0 = 500.0;
                            var t = 0.0, v;
                            var time = this.options.time * 1000;//匀速运行的时间，单位秒

                            $(click).on('click', function () {
                                if (!flg) {
                                    flg = true;
                                    target = $this.target || Math.floor(Math.random() * allNumber + 1);
                                    speedUp();
                                } else {
                                    return;
                                }
                            });



                            //加速
                            function speedUp() {
                                runner(ix);
                                if (v <= 50) {
                                    clearTimeout(stop);
                                    v = 50;
                                    t = 0.0;
                                    uniform(); //跳转到匀速
                                } else {
                                    t++;
                                    v = v0 + a * t;
                                    stop = setTimeout(speedUp, v);
                                }
                            }
                            //匀速
                            function uniform() {
                                stop = setTimeout(uniform, v);
                                if (t == time / 50) {
                                    clearTimeout(stop);
                                    t = 0.0;
                                    speedDown();
                                } else {
                                    t++;
                                }
                                runner(ix);
                            }
                            //减速
                            function speedDown() {
                                var stop3 = setTimeout(speedDown, v);
                                if (v >= 500) {
                                    v = 500;
                                    if (ix == target - 1) {
                                        clearTimeout(stop3);
                                        options.end(target);
                                        flg = false;
                                    }
                                } else {
                                    t++;
                                    v = v - a * t;
                                }
                                runner(ix);
                            }
                            //ix++
                            function runner(i) {
                                children.removeClass('on').eq(ix).addClass('on');
                                i++;
                                if (i == allNumber) {
                                    ix = 0;
                                } else {
                                    ix = i;
                                }
                            }
                        },
                        setTarget: function (options) {
                            var $this = this.$element;
                            $this.target = options;
                        }
                    }
                    $.fn.myLuckDraw = function (options, target) {
                        var Ld = new LuckDraw(this, options);
                        Ld.setTarget(target);
                        Ld.init();
                        return this;
                    }
                })(jQuery, window, document);

            //抽奖js配置项
            $(function () {
                //抽奖商品中哪个请求数据
                $.ajax({
                    url: C.interface.choujiang,
                    type: 'post',
                    dataType: 'json',
                    data: {
                        phone: C.phone,
                        pwd: C.pwd,
                        token: C.token
                    },
                    success: function (response) {
                        if (response.errorCode == '200') {
                            var data = response.data;
                            var giftName = data.giftname;
                            localStorage.setItem('giftName',giftName);
                            $('.tur-alert-box').html(choujiangCmp(data.gift));


                            //tar中奖号
                            var tar = data.gift.activity_id;
                            var winnerId = data.winnerId;
                            //配置项
                            $('.cj1').myLuckDraw({
                                row: 3, //行
                                column: 3, //列
                                spacing: 5, //空隙
                                click: '.bt1', //点击触发
                                time: 3,//匀速运动的时间
                                end: function (e) {
                                    //抽奖执行完毕的回调函数,参数e为获奖编号
                                    //因为这里是指定的，所以e == 12
                                    // $('.jg1 em').text(e);
                                    console.log('您抽中了第' + e + '个奖品');
                                    giftShow();
                                }
                            }, tar); //这里tar是确定想要抽奖的目标是几号

                            //关闭中奖弹框
                            $('.tur-close-alert').click(giftClose);

                            //点击立即领取
                            $('.gift-pull').click(function () {
                                window.location.href = 'turnplate_info.html?winnerId='+winnerId
                            })

                        } else if (response.errorCode == '0') {

                        } else {
                            alert(response.errorMsg);
                        }
                    }
                });
            });
        } else if (response.errorCode == '0') {

        } else {
            $('.isEnoughPrent').show();
        }
    }
});

//无缝滚动
$('.scroll-list li:even').addClass('lieven');
$(function () {
    $(".scroll-list").myScroll({
        speed: 40, //数值越大，速度越慢
        rowHeight: 30 //li的高度
    });
});*/


